import Tooltip from '@/components/tooltip'
import styles from './index.module.less'
import cm from 'classnames'
import DateRanger from '@/components/dateranger'
import * as echarts from 'echarts'
import { useEffect, useMemo, useRef, useState } from 'react'
import QuestionSvg from '@/svg/question'
import { statisticArr, generateOption } from './util'
import ScrollHorizonMenu from '@/components/scroll-horizon-menu'
import { getDataView, getDataList } from '@/api'
import AdminAuthority from '@/components/admin-authority'
import Big from 'big.js'
import UserSelect from '@/components/user-select'
import { currUserRoles,userinfo } from '@/store'
import { useRecoilValue } from 'recoil'
import { ADMIN_ID } from '@/constant'
import { formatNumber } from '@/utils/utils'
import { useCacheSessionData } from '@/utils/hooks'

const Index = () => {
  const user = useRecoilValue(userinfo)
  const [cacheDate, updateCacheDate, clearDate] = useCacheSessionData('data_overview')
  const currentRole = useRecoilValue(currUserRoles)
  const echartDomRef1 = useRef(null)
  const echartRef = useRef(null)
  const [dataType, setStatic] = useState(1)
  const [selectedDate, setSelectedDate] = useState(
    cacheDate ? { startDate: cacheDate.startDate, endDate: cacheDate.endDate } : DateRanger.LAST7DAYS
  )
  const [staticData, setStaticData] = useState({})
  const [userIds, setUserIds] = useState(
    currentRole.current.actorType === ADMIN_ID ? undefined : [user.id]
  )
  // 获取营销数据总览
  const getDataStatistic = async (data) => {
    const res = await getDataView(data)
    if (!res.code) {
      setStaticData(res.data)
    }
  }
  //获取营销数据列表
  const getList = async (data) => {
    const res = await getDataList(data)
    if (!res.code) {
      const data = (res.data?.list || []).map((item) => {
        if ([4, 5].includes(dataType)) {
          item.data = Big(item.data).div(100).toFixed(2).toString()
        }
        return item.data
      })
      if (!data.length) {
        data.push(0, 0, 0, 0, 0, 0)
      }
      const currItem = statisticArr.find((item) => item.id === dataType)
      const newOptions = generateOption({
        echarts,
        data,
        name: currItem.label,
        isMoney: currItem.isMoney,
        date: { start: selectedDate.startDate, end: selectedDate.endDate },
        hasPercentage: true,
      })
      echartRef.current.setOption(newOptions, true)
    }
  }

  const statisticParams = useMemo(() => {
    return { startTime: selectedDate.startDate, endTime: selectedDate.endDate, userIds }
  }, [selectedDate, userIds])

  const listParams = useMemo(() => {
    return {
      startTime: selectedDate.startDate,
      endTime: selectedDate.endDate,
      dataType,
      userIds,
    }
  }, [dataType, selectedDate, userIds])

  const updateIds = (data) => {
    setUserIds([...new Set(data)])
  }

  // 时间段修改
  const updateDate = (date) => {
    updateCacheDate(date)
    setSelectedDate(date)
  }

  //初始化 ECharts 实例&设置随着窗口大小变化，表格变化
  useEffect(() => {
    echartRef.current = echarts.init(echartDomRef1.current)
    const resizeEchart = () => {
      echartRef.current.resize()
    }
    window.addEventListener('resize', resizeEchart)
    return () => {
      window.removeEventListener('resize', resizeEchart)
    }
  }, [])

  useEffect(() => {
    getDataStatistic(statisticParams)
  }, [userIds, selectedDate])

  useEffect(() => {
    getList(listParams)
  }, [dataType, selectedDate, userIds])

  useEffect(() => {
    return () => {
      clearDate()
    }
  }, [])
  return (
    <div className={styles.home}>
      <div className="flex justify-between mb-10 pr-10">
        <DateRanger direction="left" onChange={updateDate} initDate={cacheDate ? cacheDate.dateObj : ''} />
        <AdminAuthority>
          <UserSelect onSubmit={(ids) => updateIds(ids)} />
        </AdminAuthority>
      </div>
      <ScrollHorizonMenu>
        {statisticArr.map((item, index) => {
          const TipDom = (
            <div className="tooltips">
              <QuestionSvg className="w-4 h-4 mr-1" fill="var(--theme-color)" />
              <span>{item.tooltip}</span>
            </div>
          )
          let count = 0
          try {
            count = staticData[item.key] || 0
          } catch (error) {}
          if (['orderAmount', 'proportionAmount'].includes(item.key)) {
            count = Big(count).div(100).toFixed(2).toString()
          }
          return (
            <div
              className={cm(styles.statisticItem, item.id === dataType ? styles.staActive : '')}
              key={index}
              onClick={() => setStatic(item.id)}
            >
              <div className={styles.itemInfo}>
                <div className={styles.infoTop}>
                  <span>{item.label}</span>
                  <Tooltip text={TipDom} />
                </div>
                <div className={cm(styles.infoBottom, !item.tip ? styles.notip : '')}>
                  {item.unit ? <span className={styles.unit}>{item.unit}</span> : null}
                  <span className={styles.amount}>
                    {formatNumber(count, item.isMoney)}
                    {count >= 10000 && <span style={{ fontSize: 12, transform: 'scale(0.5)' }}>w</span>}
                  </span>
                </div>
              </div>
              <img src={item.icon} className={styles.itemImg} />
            </div>
          )
        })}
      </ScrollHorizonMenu>
      <div className={cm(styles.content, 'flex-1')}>
        <div className={styles.contentChart} ref={echartDomRef1}></div>
      </div>
    </div>
  )
}

export default Index
